package wypozyczalnia.controller;

import java.security.Principal;
import java.text.ParseException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibm.icu.text.SimpleDateFormat;

//import wypozyczalnia.domain.Car;
import wypozyczalnia.domain.Hire;
import wypozyczalnia.domain.User;
import wypozyczalnia.forms.RentForm;
import wypozyczalnia.service.CarService;
import wypozyczalnia.service.HireService;
import wypozyczalnia.service.UserService;

@Controller
@RequestMapping(value = "/rent/*")
public class RentCotroller {
	
	private final Logger logger = Logger.getLogger(RentCotroller.class);
	
//	@Autowired
//	CarService carService;
	
	@Autowired
	HireService hireService;
	@Autowired
	UserService userService;
	
	
	@RequestMapping(value = "confirm.do")
	public String confirmRent(HttpSession session, HttpServletResponse response,
			 HttpServletRequest request, Model model, Integer id) {
		logger.info("car rent confirmed. car id: " + id);
//		Car car = carService.getCarById(id);
//		model.addAttribute("recentlyRentedCar", car);
		return "rentConfirmation";
		
	}

	@RequestMapping(value = "rent.do")
	public String rentACar(HttpSession session, HttpServletResponse response,
			RentForm form, HttpServletRequest request, Model model, Principal principal) {
		if (form.getChoice().equals("TAK")) {
//			Car rentedCar = carService.getCarById(form.getId());
//			rentedCar.setAvalible(false);
//			carService.update(rentedCar);

			String currentUserName = principal.getName();
			User user = userService.getUserByUsername(currentUserName);
			
			logger.debug(form.getRentDateFrom() + " " + form.getRentDateTo());
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
			Date from = new Date();
			Date to = new Date();
			try {
				from = sdf.parse(form.getRentDateFrom());
			    to = sdf.parse(form.getRentDateTo());
				logger.debug(sdf.parse(form.getRentDateFrom()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
//			Hire newHire = new Hire(from, to, false,user,rentedCar);
			
//			hireService.create(newHire);
			return "reservationSucces";
		} else {
			return "start";
		}
	}
}
